
// 160.相交链表
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        // 先判断两个链表是否相交, 只用看尾节点是否相同即可
        ListNode *curA = headA , *curB = headB;
        int countA = 1 , countB = 1;
        while(curA->next) 
        {
            curA = curA->next ;
            countA++;
        } 
        while(curB->next) 
        {
            curB = curB->next ;
            countB++;
        } 

        if(curA != curB) return nullptr;
        // 求两个链表长度之差
        ListNode *l_list = headA , *s_list = headB;
        if(countB > countA) l_list = headB , s_list = headA;
        int x = abs(countA - countB);
        for(int i = 0 ; i < x ; i++) l_list = l_list->next;
        while(s_list != l_list) 
        {
            s_list = s_list->next;
            l_list = l_list->next;
        }
        return s_list;
    }
};